from fastapi import Depends, Request
from models.taggingDemo import TaggingDemo
from schemas.baseResponse import page_list
from schemas.demoDto import  DemoFormRequest, DemoListRequest, DemoResponse
from database.database import get_db
from sqlalchemy.orm import Session

from utils.businessException import BusinessException


class DemoService:
    def __init__(self, request: Request, db: Session = Depends(get_db)):
        self.db = db
        self.request = request

    def _query_demo(self):
        return self.db.query(TaggingDemo).filter(TaggingDemo.is_deleted == False)
    
    # 列表
    def list(self, request=DemoListRequest):
        # query2 = self.db.query(TaggingDemo).all()
        query = self._query_demo()
        if request.name: query = query.filter(TaggingDemo.name.like(f"%{request.name}%"))

        query = query.order_by(TaggingDemo.update_time.desc())

        return page_list(query, request.page_index, request.page_size, True)
    
    # 根据 ID 删除
    async def delete(self, id: int):
        data = self._query_demo().filter(TaggingDemo.id == id).first()
        data.delete(self.request.state.user.id)
        self.db.commit()
        return True

    # add
    async def add(self, request: DemoFormRequest):
        db = self.db
        await self.check_form(request)
        data = TaggingDemo()
        data = self.set_model(data, request)
        db.add(data)
        db.commit()
        return data.id

    # update
    async def update(self, request: DemoFormRequest):
        await self.check_form(request)
        data = self._query_demo().filter(TaggingDemo.id == request.id).first()
        if data is None: raise BusinessException("数据不存在")
        data = self.set_model(data, request)
        data.set_update_operation(self.request.state.user.id)
        return True
    
    # 赋值给model
    def set_model(self, model: TaggingDemo, request: DemoFormRequest):
        model.name = request.name
        model.age = request.age
        return model
    # check from
    async def check_form(self, request: DemoFormRequest):
        if not request.name: raise BusinessException("名称不能为空")
        # 该名称已存在
        query = self._query_demo().filter(TaggingDemo.name == request.name)
        if request.id!=None: query = query.filter(TaggingDemo.id != request.id)
        if len(query.all()) > 0: raise BusinessException("该名称已存在")